package com.sendpo.zjx.sendpo.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.Gson;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.domain.MerchandiseDomain;
import com.sendpo.zjx.sendpo.domain.MerevaluateDomain;
import com.sendpo.zjx.sendpo.domain.UserDomain;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.table.MerchandiseCollection;
import com.sendpo.zjx.sendpo.table.MerchandiseHistory;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.utils.MD5Util;
import com.sendpo.zjx.sendpo.utils.OrderInfoUtil2_0;
import com.sendpo.zjx.sendpo.utils.PayDomain;
import com.sendpo.zjx.sendpo.utils.PayResult;
import com.sendpo.zjx.sendpo.utils.QRCodeUtils;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;
import com.sendpo.zjx.sendpo.views.MainScrollview;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.common.util.DensityUtil;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import me.shaohui.bottomdialog.BottomDialog;
import me.zhanghai.android.materialratingbar.MaterialRatingBar;

/**
 * Created by Administrator on 2017/8/17.
 */

public class GeneicStoreInfoActivity extends AppCompatActivity {


    @BindView(R.id.backbt)
    RelativeLayout backbt;
    @BindView(R.id.head)
    RelativeLayout head;
    @BindView(R.id.addgouwu_tv)
    TextView addgouwuTv;
    @BindView(R.id.addgouwu_bt)
    RelativeLayout addgouwuBt;
    @BindView(R.id.buy_bt)
    RelativeLayout buyBt;
    @BindView(R.id.gener_ll)
    LinearLayout generLl;
    @BindView(R.id.tiqianyuyue_bt)
    Button tiqianyuyueBt;
    @BindView(R.id.tiqianyuyue_rl)
    RelativeLayout tiqianyuyueRl;
    @BindView(R.id.danmaiprice_tv)
    TextView danmaipriceTv;
    @BindView(R.id.danmai_bt)
    RelativeLayout danmaiBt;
    @BindView(R.id.pindanprice_tv)
    TextView pindanpriceTv;
    @BindView(R.id.pindanbuy_bt)
    RelativeLayout pindanbuyBt;
    @BindView(R.id.pindan_rl)
    LinearLayout pindanRl;
    @BindView(R.id.bottom)
    LinearLayout bottom;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.price_tv)
    TextView priceTv;
    @BindView(R.id.song_tv)
    TextView songTv;
    @BindView(R.id.xiandao_tv)
    TextView xiandaoTv;
    @BindView(R.id.dajianjia_tv)
    TextView dajianjiaTv;
    @BindView(R.id.origin_tv)
    TextView originTv;
    @BindView(R.id.merchat_img_iv)
    CircleImageView merchatImgIv;
    @BindView(R.id.merchat_name)
    TextView merchatName;
    @BindView(R.id.merchat_bt)
    RelativeLayout merchatBt;
    @BindView(R.id.click_createwx)
    TextView clickCreatewx;
    @BindView(R.id.info)
    TextView info;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.maincrollview)
    MainScrollview maincrollview;
    @BindView(R.id.head_img)
    ImageView headImg;
    @BindView(R.id.kucun_tv)
    TextView kucunTv;

    private LinearLayoutManager lm;
   @BindView(value = R.id.active_tv)
   public TextView activeTv;
    private boolean isGouwuCar = false;
    BottomDialog bottomDialog;
    public Tencent tencent = null;

    private int merchandiseId = 0;

    public MerchandiseDomain domain;
    private String current_price = "0.00";
    private String origin_price = "0.00";
    public int jifentype = 0;
    private Dialog paydialog;
    public Dialog loadingdialog = null;
    public Dialog confirm_dialog = null;
    private RadioGroup radioGroup;
    private boolean lastloading = false;
    private RecylcerAdaper adpter;
    private int currentlastitem = 0;
    private int pagenow = 1;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HttpUrl.SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Gson gson = new Gson();
                        PayDomain pay = gson.fromJson(payResult.getResult(), PayDomain.class);
                        //     paysuccess(orderId);
                        disanfang(domain.getData().getMerchandiseYuyuefee());
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        System.out.println("***************" + payResult.getResult());
                        //   Toast.makeText(getApplicationContext(), "支付成功", Toast.LENGTH_SHORT).show();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(getApplicationContext(), "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

                default:
                    break;
            }
        }

        ;
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_geneicstoreinfo);
        ButterKnife.bind(this);
        merchandiseId = getIntent().getIntExtra("merchandiseId", 0);
        Tools.initStatus(this, R.color.black);
        initComponent();
        initShare();
        initQuery(merchandiseId + "");
        initPayDialog();
        query(pagenow, merchandiseId + "");
        DbManager dbManager = Tools.getDbManager(getApplication(), Tools.DBNAME, Tools.DBVERSION);
        try {
            MerchandiseCollection cb = dbManager.selector(MerchandiseCollection.class).where("merchandiseId", "=", merchandiseId)
                    .findFirst();
            if (cb != null) {
                isGouwuCar = true;
                addgouwuBt.setBackgroundColor(getResources().getColor(R.color.default_theme));
                addgouwuTv.setTextColor(getResources().getColor(R.color.white));
                addgouwuTv.setText("已加入收藏");
            } else {
                isGouwuCar = false;
                addgouwuBt.setBackgroundColor(getResources().getColor(R.color.default_theme));
                addgouwuTv.setTextColor(getResources().getColor(R.color.white));
                addgouwuTv.setText("加入收藏");
            }
        } catch (DbException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        webUserServer();
    }

    private void initComponent() {
        lm = new LinearLayoutManager(this, OrientationHelper.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        recyclerview.setLayoutManager(lm);
        originTv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);//下划线
        originTv.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中间横线
        originTv.getPaint().setAntiAlias(true);// 抗锯齿
        originTv.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);  // 设置中划线并加清晰
    }

    @OnClick(value = {R.id.backbt, R.id.buy_bt, R.id.addgouwu_bt,
            R.id.click_createwx, R.id.tiqianyuyue_bt,
            R.id.danmai_bt,
            R.id.pindanbuy_bt})
    public void onMyClick(View view) {
        switch (view.getId()) {
            case R.id.backbt:
                finish();
                break;
            case R.id.buy_bt:
                Map<String, Object> map = new HashMap<>();
                map.put("data", domain.getData());
                map.put("type", 0);
                Tools.redirectActivity(this, BuyGenericStoreActivity.class, map);
                break;
            //    case R.id.more_bt:
            //       Tools.redirectActivity(this, UserGuestActivity.class);
            //      break;
            case R.id.addgouwu_bt:
                if (isGouwuCar) {
                    isGouwuCar = false;
                    addgouwuBt.setBackgroundColor(getResources().getColor(R.color.default_theme));
                    addgouwuTv.setTextColor(getResources().getColor(R.color.white));
                    addgouwuTv.setText("加入收藏");
                    if (domain != null) {
                        DbManager dbManager = Tools.getDbManager(getApplication(), Tools.DBNAME, Tools.DBVERSION);
                        try {
                            MerchandiseCollection cb = dbManager.selector(MerchandiseCollection.class).where("merchandiseId", "=", domain.getData().getMerchandiseId())
                                    .findFirst();
                            dbManager.delete(cb);
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    isGouwuCar = true;
                    addgouwuBt.setBackgroundColor(getResources().getColor(R.color.default_theme));
                    addgouwuTv.setTextColor(getResources().getColor(R.color.white));
                    addgouwuTv.setText("已加入收藏");
                    if (domain != null) {
                        DbManager dbManager = Tools.getDbManager(getApplication(), Tools.DBNAME, Tools.DBVERSION);
                        try {
                            MerchandiseCollection mc = new MerchandiseCollection();
                            mc.setCreatedate(new Date().getTime() + "");
                            mc.setMerchandiseCurrentprice(domain.getData().getMerchandiseCurrentprice());
                            mc.setMerchandiseOriginalprice(domain.getData().getMerchandiseOriginalprice());
                            mc.setMerchandiseDetails(domain.getData().getMerchandiseDetails());
                            mc.setMerchandiseHeadimg(domain.getData().getMerchandiseHeadimg());
                            mc.setMerchandiseId(domain.getData().getMerchandiseId());
                            mc.setMerchandiseName(domain.getData().getMerchandiseName());
                            dbManager.save(mc);
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    }

                }
                break;
//            case R.id.share_bt:
//                bottomDialog.show();
//                break;
            case R.id.click_createwx:

                break;
            case R.id.tiqianyuyue_bt:
                List<User> userList = Xutils.queryAll(getApplication(), User.class);
                if (userList == null || userList.size() == 0) {
                    Tools.redirectActivity(GeneicStoreInfoActivity.this, LoginActivity.class);
                    return;
                }
                User user=userList.get(0);
                if (domain == null) {
                    return;
                }
//                paydialog.show();

                JSONObject jsonObject=new JSONObject();
                try {
                    jsonObject.put("userId",""+user.getUserId());
                    jsonObject.put("userAddressId",""+0);
                    jsonObject.put("deliveryType",""+1);
                    jsonObject.put("price",""+"0.00");
                    jsonObject.put("originalPrice",""+domain.getData().getMerchandiseOriginalprice());
                    JSONArray jsonArray=new JSONArray();

                    JSONObject rea=new JSONObject();
                    rea.put("productId",""+domain.getData().getMerchandiseId());
                    rea.put("price","0.00");
                    if(domain.getData().getMerchantsId()==1){
                        rea.put("type","2");
                    }else{
                        rea.put("type","1");
                    }
                    rea.put("count","1");
                    jsonArray.put(rea);
                    jsonObject.put("relations",jsonArray);
                    createorder(jsonObject);
                } catch (JSONException e) {
                    e.printStackTrace();
                }


                break;
            case R.id.danmai_bt:
                Map<String, Object> danmai = new HashMap<>();
                MerchandiseDomain.DataBean dat = domain.getData();
                dat.setMerchandiseCurrentprice(origin_price);
                danmai.put("data", dat);
                danmai.put("type", 1);
                Tools.redirectActivity(this, BuyGenericStoreActivity.class, danmai);
                break;
            case R.id.pindanbuy_bt:
                Map<String, Object> pindanbuy = new HashMap<>();
                MerchandiseDomain.DataBean dat1 = domain.getData();
                dat1.setMerchandiseCurrentprice(current_price);
                pindanbuy.put("data", dat1);
                pindanbuy.put("type", 1);
                Tools.redirectActivity(this, BuyGenericStoreActivity.class, pindanbuy);
                break;

        }
    }

    public class RecylcerAdaper extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        public List<MerevaluateDomain.DataBean> dataBeen;
        public LayoutInflater inflater;

        public RecylcerAdaper(List<MerevaluateDomain.DataBean> dataBeen, Context context) {
            inflater = LayoutInflater.from(context);
            this.dataBeen = dataBeen;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            RecyclerView.ViewHolder ih = null;

            ih = new IndexHoler(inflater.inflate(R.layout.layout_userguestlistitem, parent, false));
            return ih;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            final IndexHoler ih = (IndexHoler) holder;
            MerevaluateDomain.DataBean dataBean = dataBeen.get(position);
            Glide.with(GeneicStoreInfoActivity.this)
                    .load("" + dataBean.getUserAvatarpath())
                    .asBitmap()
                    .placeholder(R.drawable.nim_avatar_default)
                    .override(300, 300)
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                            ih.cir_icon.setImageBitmap(resource);
                        }
                    });
            ih.username.setText("" + dataBean.getUserName());
            ih.startbar.setRating(Float.parseFloat(dataBean.getStarscount()));
            ih.rootView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                }
            });
            ih.text.setText("" + dataBean.getContentText());
            ih.datetime.setText("" + Tools.getDateBeforeAfter(Tools.getStringtoDate(dataBean.getEvalutateCreatetime(),
                    "yyyy-MM-dd HH:mm:ss")));


        }

        @Override
        public int getItemCount() {
            return dataBeen.size();
        }

        public class IndexHoler extends RecyclerView.ViewHolder {
            public View rootView;

            public CircleImageView cir_icon;
            public MaterialRatingBar startbar;
            public TextView username;
            public TextView text;
            public TextView datetime;

            public IndexHoler(View itemView) {
                super(itemView);
                rootView = itemView;
                cir_icon = itemView.findViewById(R.id.cir_icon);
                startbar = itemView.findViewById(R.id.startbar);
                startbar.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View view, MotionEvent motionEvent) {
                        return true;
                    }
                });
                username = itemView.findViewById(R.id.username);
                text = itemView.findViewById(R.id.text);
                datetime = itemView.findViewById(R.id.datetime);
            }
        }

        public void initRefresh(List<MerevaluateDomain.DataBean> domains) {
            this.dataBeen.removeAll(this.dataBeen);
            this.dataBeen.addAll(domains);
            notifyDataSetChanged();
        }

        public void initAppend(List<MerevaluateDomain.DataBean> domains) {
            this.dataBeen.addAll(domains);
            notifyDataSetChanged();
        }

        public void delete(int position) {
            this.dataBeen.remove(position);
            notifyDataSetChanged();
        }
    }

    //QQ腾讯好友分享
    private void onClickQQShare() {

        Bundle data = new Bundle();
        data.putString(QQShare.SHARE_TO_QQ_APP_NAME, getResources().getString(R.string.app_name));
        data.putString(QQShare.SHARE_TO_QQ_TITLE, "产品标题");
        data.putString(QQShare.SHARE_TO_QQ_SUMMARY, "产品描述");
        data.putString(QQShare.SHARE_TO_QQ_TARGET_URL, "http://www.baidu.com");
        data.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,
                "http://images.3158.cn/data/attachment/tougao/article/2015/12/17/df0b92921cb9fa8bb4f82c18ad1e08ba.jpg");
        data.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        data.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_ITEM_HIDE);
        tencent.shareToQQ(this, data, new QQShareUiListener());
    }

    public void initShare() {
        bottomDialog = BottomDialog.create(getSupportFragmentManager());
        bottomDialog.setViewListener(new BottomDialog.ViewListener() {
            @Override
            public void bindView(View v) {
                v.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        bottomDialog.dismiss();
                    }
                });
                View qqsapce = v.findViewById(R.id.qqspace_bt);
                qqsapce.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        shareToQzone();
                    }
                });
                View qq_bt = v.findViewById(R.id.qq_bt);
                qq_bt.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        onClickQQShare();
                    }
                });

                View exit = v.findViewById(R.id.closebt);
                exit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        bottomDialog.dismiss();
                    }
                });
            }
        });
        bottomDialog.setLayoutRes(R.layout.layout_dialog_share);
        bottomDialog.setDimAmount(0.5f);
        bottomDialog.setCancelOutside(true);
        bottomDialog.setTag("BottomDialog");
        tencent = Tencent.createInstance(HttpUrl.QQ_KEY, getApplicationContext());

    }


    public void initPayDialog() {
        loadingdialog = new Dialog(this);
        loadingdialog.setContentView(R.layout.dialog_loading);
        loadingdialog.setCanceledOnTouchOutside(false);
        loadingdialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        confirm_dialog = new Dialog(this);
        confirm_dialog.setContentView(R.layout.dialog_paymoney);
        confirm_dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        final EditText confirm_edit_tv = confirm_dialog.findViewById(R.id.edit_tv);
        TextView exitbt = confirm_dialog.findViewById(R.id.exitbt);
        exitbt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                confirm_dialog.dismiss();
            }
        });
        final TextView readby = confirm_dialog.findViewById(R.id.readby);
        readby.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                System.out.println("***********************readby");
                if (TextUtils.isEmpty(confirm_edit_tv.getText().toString().trim())) {
                    Toast.makeText(getApplicationContext(), "密码不能为空", Toast.LENGTH_LONG).show();
                    return;
                }
                List<User> userList = Xutils.queryAll(getApplication(), User.class);
                if (userList == null) {
                    Tools.redirectActivity(GeneicStoreInfoActivity.this,LoginActivity.class);
                    return;
                }
                User user = userList.get(0);

                if (TextUtils.equals(MD5Util.getMD5(confirm_edit_tv.getText().toString().trim()), user.getUserPaypassword())) {
                  //  reduceMoney(domain.getData().getMerchandiseYuyuefee());
                    confirm_dialog.dismiss();
                    //   reduceMoney(paymoney+"",orderId);


                } else {
                    Toast.makeText(getApplicationContext(), "输入支付密码不正确", Toast.LENGTH_LONG).show();
                }

            }
        });

        paydialog = new Dialog(this);
        paydialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        paydialog.setContentView(R.layout.dialog_rechargemoney);
        radioGroup = paydialog.findViewById(R.id.rg_pay);
        TextView recharage_title = paydialog.findViewById(R.id.recharage_title);
        recharage_title.setText("结算支付");
        EditText recharge_edit = paydialog.findViewById(R.id.recharge_edit);
        recharge_edit.setVisibility(View.GONE);
        View yuyue_left = paydialog.findViewById(R.id.yuyue_left);
        yuyue_left.setVisibility(View.VISIBLE);
        final RadioButton pay_moneypackage = paydialog.findViewById(R.id.pay_moneypackage);
        pay_moneypackage.setVisibility(View.VISIBLE);
        pay_moneypackage.setChecked(true);
        final RadioButton pay_wexin = paydialog.findViewById(R.id.pay_wexin);
        pay_wexin.setChecked(false);
        paydialog.findViewById(R.id.moneycount_rl);

        Button paybt = paydialog.findViewById(R.id.paybt);

        paybt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                List<User> userList = Xutils.queryAll(getApplication(), User.class);
                if (userList == null) {
                    return;
                }
                User user = userList.get(0);
                switch (radioGroup.getCheckedRadioButtonId()) {
                    case R.id.pay_moneypackage:

                        if (TextUtils.isEmpty(user.getUserPaypassword())) {
                            Intent paypass = new Intent(GeneicStoreInfoActivity.this, ModifyPayPassActivity.class);
                            startActivity(paypass);
                            return;
                        }
                        paydialog.dismiss();
                        confirm_edit_tv.getText().clear();
                        confirm_dialog.show();
                        break;
                    case R.id.pay_wexin:
                        Toast.makeText(getApplicationContext(), "微信支付"
                                , Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.pay_paypackage:
                        //paymoney
                        Toast.makeText(getApplicationContext(), "打开支付宝", Toast.LENGTH_SHORT).show();
                        if (domain.getData().getMerchandiseYuyuefee().equals("0.00")) {
                            disanfang(domain.getData().getMerchandiseYuyuefee());
                            confirm_dialog.dismiss();
                            return;
                        }
                        payV2("0.01", "深圳送宝网科技有限公司-送宝", domain.getData().getMerchandiseYuyuefee() + "(元)" + domain.getData().getMerchandiseName());
                        confirm_dialog.dismiss();
                        break;
                }
            }
        });
        yuyue_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pay_moneypackage.setChecked(true);
            }
        });
        RelativeLayout wx_rl = paydialog.findViewById(R.id.wx_rl);
        wx_rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pay_wexin.setChecked(true);
            }
        });
        final RadioButton pay_paypackage = paydialog.findViewById(R.id.pay_paypackage);
        RelativeLayout pay_rl = paydialog.findViewById(R.id.pay_rl);
        pay_rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pay_paypackage.setChecked(true);
            }
        });


    }

    //QQ分享监听
    private class QQShareUiListener implements IUiListener {

        @Override
        public void onComplete(Object o) {
            System.out.println("********" + o.toString());

        }

        @Override
        public void onError(UiError uiError) {
            Toast.makeText(getApplicationContext().getApplicationContext(), uiError.errorDetail, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel() {

        }
    }

    //QQ腾讯分享空间
    private void shareToQzone() {
//分享类型
        Bundle params = new Bundle();
        params.putString(QzoneShare.SHARE_TO_QQ_APP_NAME, getResources().getString(R.string.app_name));
        params.putString(QQShare.SHARE_TO_QQ_TITLE, "产品标题");
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, "产品描述");
        params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, "http://wapi.jiechennuo.com/wifijz.apk");
        params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
        ArrayList<String> strings = new ArrayList<String>();
        strings.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1491909596292&di=8d177470e12744ff9eba0f7f55a89c78&imgtype=0&src=http%3A%2F%2Fwww.pp3.cn%2Fuploads%2F201611%2F2016120301.jpg");
        params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, strings);
        tencent.shareToQzone(this, params, new QQShareUiListener());
    }


      //无条件免费
    public void  createorder(final JSONObject jsonObject){
        RequestParams requestParams=new RequestParams(HttpUrl.generateOrder);
        requestParams.setAsJsonContent(true);
        System.out.println("************************"+jsonObject.toString());
        requestParams.setBodyContent(jsonObject.toString());
        x.http().post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject1=new JSONObject(result);
                    if(jsonObject1.getBoolean("flag")){
                        Toast.makeText(getApplicationContext(),"预约成功",Toast.LENGTH_SHORT).show();

                    }else{
                        Toast.makeText(getApplicationContext(),"预约失败，一人限购一次 ",Toast.LENGTH_SHORT).show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(getApplicationContext(),"请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }



    public void initQuery(final String id) {
        Map<String, String> map = new HashMap<>();
        map.put("merchandiseId", "" + id);
        Xutils.POST(HttpUrl.merchandisebymerchaniseid, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(final String result) {
                Gson gson = new Gson();
                domain = gson.fromJson(result, MerchandiseDomain.class);
                if (domain == null || domain.getData() == null) {
                    return;
                }
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        current_price = domain.getData().getMerchandiseCurrentprice();
                        origin_price = domain.getData().getMerchandiseOriginalprice();
                        activeTv.setText(""+domain.getData().getActivityDetails());
                        addHistory(domain.getData());
                        name.setText("" + domain.getData().getMerchandiseName());
                        Glide.with(GeneicStoreInfoActivity.this)
                                .load("" + domain.getData().getMerchandiseHeadimg())
                                .asBitmap()
                                .centerCrop()
                                .animate(R.anim.fade_in)
                                .placeholder(getResources().getColor(R.color.default_lightgray))
                                .into(headImg);
                        originTv.setText("原价：¥" + domain.getData().getMerchandiseOriginalprice());
                        priceTv.setText("现价：¥" + domain.getData().getMerchandiseCurrentprice());
                         info.setText(domain.getData().getMerchandiseDetails());
                        if (domain.getData().getMerchantsId() != 1) {
                            merchatBt.setVisibility(View.VISIBLE);
                            Glide.with(GeneicStoreInfoActivity.this)
                                    .load("" + domain.getData().getMerchantsAvatarpath())
                                    .asBitmap()
                                    .placeholder(R.drawable.nim_avatar_default)
                                    .animate(R.anim.fade_in)
                                    .placeholder(getResources().getColor(R.color.default_lightgray))
                                    .into(merchatImgIv);
                            merchatBt.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    Map<String, Object> map = new HashMap<>();
                                    map.put("merchantsId", domain.getData().getMerchantsId());
                                    Tools.redirectActivity(GeneicStoreInfoActivity.this, StoreMainAllProduceActivity.class, map);
                                }
                            });
                            merchatName.setText("" + domain.getData().getMerchantsName());
                        } else {
                            merchatBt.setVisibility(View.GONE);
                        }
                        kucunTv.setText("库存数量：" + domain.getData().getMerchandiseCount());
                        clickCreatewx.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                final Dialog dialog = new Dialog(GeneicStoreInfoActivity.this);
                                dialog.setContentView(R.layout.dialog_erweima);
                                dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                                ImageView iv = dialog.findViewById(R.id.img);
                                dialog.findViewById(R.id.rootview).setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        dialog.dismiss();
                                    }
                                });
                                JSONObject jb = new JSONObject();
                                try {
                                    jb.put("merchandiseId", domain.getData().getMerchandiseId());
                                    jb.put("merchantsId", domain.getData().getMerchantsId());
                                    jb.put("userId", domain.getData().getUserId());
                                    Bitmap resource = QRCodeUtils.getQRImage("" + jb.toString(), DensityUtil.dip2px(300),
                                            DensityUtil.dip2px(300), null);
                                    iv.setImageBitmap(resource);
                                    dialog.show();
                                    Toast.makeText(getApplicationContext(), "生成二维码成功", Toast.LENGTH_SHORT).show();
                                } catch (Exception x) {
                                    x.printStackTrace();
                                    Toast.makeText(getApplicationContext(), "生成二维码失败", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                        System.out.println("*************************"+domain.getData().getGiveMethod());
                        if(domain.getData().getGiveMethod()==0){
                            generLl.setVisibility(View.GONE);
                            tiqianyuyueRl.setVisibility(View.VISIBLE);
                        }else{
                            generLl.setVisibility(View.VISIBLE);
                            tiqianyuyueRl.setVisibility(View.GONE);
                        }

                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    public void payV2(String total_account, String title, String content) {
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(HttpUrl.PAY_APPID, total_account, title, content, false);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
        String privateKey = HttpUrl.PAY_RSA_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, false);
        final String orderInfo = orderParam + "&" + sign;
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(GeneicStoreInfoActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = HttpUrl.SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }



    public void disanfang(String orderMoney) {
        List<User> users = Xutils.queryAll(getApplication(), User.class);
        if (users == null || users.size() == 0) {
            return;
        }
        User user = users.get(0);
        loadingdialog.show();
        Map<String, String> map = new HashMap<>();
        map.put("userId", user.getUserId() + "");
        map.put("merchantsId", "" + domain.getData().getMerchantsId());
        map.put("merchandiseId", "" + merchandiseId);
        map.put("orderState", "2");
        map.put("orderMoney", "" + orderMoney);
        map.put("orderNumber", "1");
        map.put("orderDeliveryMethod", "1");
        map.put("orderDeliveryMoney", "0.00");
        map.put("orderBuyerMessage", "");
        map.put("userCity", "");
        map.put("userConsignee", "");
        map.put("userDetailedAddress", "");
        map.put("userIphone", "");
        map.put("orderType", "2");
        map.put("orderAllowjifen", "0");
        Xutils.POST(HttpUrl.ordermerchandiseaddtiqianyuyuedisanfang, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                loadingdialog.dismiss();
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    Toast.makeText(GeneicStoreInfoActivity.this.getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
                    switch (jsonObject.getInt("state")) {
                        case HttpCode.SUCCESS:

                            break;

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                loadingdialog.dismiss();
                Toast.makeText(getApplicationContext(), "请稍后再试", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    public void webUserServer() {
        final List<User> userList = Xutils.queryAll(getApplication(), User.class);
        if (userList == null || userList.size() == 0) {
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("userId", userList.get(0).getUserId() + "");
        Xutils.POST(HttpUrl.queryuserbyid, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                UserDomain userDomain = gson.fromJson(result, UserDomain.class);
                switch (userDomain.getState()) {
                    case HttpCode.SUCCESS:
                        User user = userDomain.getData();
                        user.setId(userList.get(0).getId());
                        Xutils.update(getApplication(), user);
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void query(int pagenow, final String merchandiseId) {
        final Map<String, String> map = new HashMap<>();
        map.put("pagenow", pagenow + "");
        map.put("merchandiseId", merchandiseId + "");
        Xutils.POST(HttpUrl.merevaluatemerchandisemr, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                MerevaluateDomain domain = gson.fromJson(result, MerevaluateDomain.class);
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        if (domain.getData() != null && domain.getData().size() != 0) {
                            if (adpter == null) {
                                recyclerview.setAdapter(adpter = new RecylcerAdaper(domain.getData(), GeneicStoreInfoActivity.this));

                            } else {
                                adpter.initRefresh(domain.getData());
                            }
                        }

                        break;
                    case HttpCode.ERROR:
                        //     Toast.makeText(getApplicationContext(), "" + domain.getMessage(), Toast.LENGTH_SHORT).show();
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    public void append(int pagenow, final String merchandiseId) {
        lastloading = true;
        final Map<String, String> map = new HashMap<>();
        map.put("pagenow", pagenow + "");
        map.put("merchandiseId", merchandiseId + "");
        Xutils.POST(HttpUrl.merevaluatemerchandisemr, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                lastloading = false;
                Gson gson = new Gson();
                MerevaluateDomain domain = gson.fromJson(result, MerevaluateDomain.class);
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        if (domain.getData() != null && domain.getData().size() != 0) {
                            if (adpter == null) {
                                recyclerview.setAdapter(adpter = new RecylcerAdaper(domain.getData(), GeneicStoreInfoActivity.this));
                            } else {
                                adpter.initAppend(domain.getData());
                            }

                        }
                        break;
                    case HttpCode.ERROR:
                        //       Toast.makeText(getApplicationContext(), "" + domain.getMessage(), Toast.LENGTH_SHORT).show();
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                lastloading = false;
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    public void addHistory(MerchandiseDomain.DataBean data) {
        DbManager db = Tools.getDbManager(this.getApplication(), Tools.DBNAME, Tools.DBVERSION);

        try {
            MerchandiseHistory db_h = db.selector(MerchandiseHistory.class)
                    .where("merchandiseId", "=", data.getMerchandiseId())
                    .findFirst();
            if (db_h != null) {
                Xutils.deleteById(getApplication(), db_h.getId(), MerchandiseHistory.class);
            }
            long count = db.selector(MerchandiseHistory.class)
                    .count();
            if (count < 10) {
                MerchandiseHistory history = new MerchandiseHistory();
                history.setCreatedate(new Date().getTime() + "");
                history.setMerchandiseCurrentprice(data.getMerchandiseCurrentprice());
                history.setMerchandiseOriginalprice(data.getMerchandiseOriginalprice());
                history.setMerchandiseDetails(data.getMerchandiseDetails());
                history.setMerchandiseHeadimg(data.getMerchandiseHeadimg());
                history.setMerchandiseId(data.getMerchandiseId());
                history.setMerchandiseName(data.getMerchantsName());
                Xutils.save(getApplication(), history);
            } else {
                db.delete(db.selector(MerchandiseHistory.class).findFirst());
                MerchandiseHistory history = new MerchandiseHistory();
                history.setCreatedate(new Date().getTime() + "");
                history.setMerchandiseCurrentprice(data.getMerchandiseCurrentprice());
                history.setMerchandiseOriginalprice(data.getMerchandiseOriginalprice());
                history.setMerchandiseDetails(data.getMerchandiseDetails());
                history.setMerchandiseHeadimg(data.getMerchandiseHeadimg());
                history.setMerchandiseId(data.getMerchandiseId());
                history.setMerchandiseName(data.getMerchantsName());
                Xutils.save(getApplication(), history);
            }

        } catch (DbException e) {
            e.printStackTrace();
        }


    }
}
